# coding: utf-8
from datetime import datetime
from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from services.datamodel.course.models import Course
from project.settings import DEFAULT_PAGESIZE


class ModelManagerIndexRecommend(BasicManager):

    def get_recommend_list(self, page):
        result = self.values().order_by("-created_at")
        paginator = Paginator(result, DEFAULT_PAGESIZE)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_list(self):
        result = IndexRecommend.objects.all()
        course_list = []
        for v in result:
            course_id_arr = v.course_ids.split(',')
            course_datas = Course.objects.filter(id__in=course_id_arr)
            course_list.append(course_datas)
            course_list.append(v)
        return course_list

    def get_list_by_student(self):
        result = IndexRecommend.objects.first()
        if result:
            ids = result.course_ids.split(',')
            course_arr = []
            for v in ids:
                id_course = Course.objects.filter(is_show=1, id=v).values("id", "name", "desc", "thumb", "students",
                                                                          "is_role").first()
                course_arr.append(id_course)
            return course_arr
        return []


class IndexRecommend(models.Model):
    course_ids = models.CharField("推荐课程", default='', max_length=500)
    name = models.CharField("名称", max_length=50)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerIndexRecommend()

    class Meta:
        verbose_name = '首页推荐'
        verbose_name_plural = verbose_name
        db_table = "momself_index_recommend"

    def __str__(self):
        return self.name


mm_Recommend = IndexRecommend.objects
